package com.lhczf.lucenedb.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: 刘华春
 * @date: 2019/2/6
 */
@Slf4j
public class FileUtil {

    private static final List<File> DELL_FAIL_FILES = new ArrayList<>();
    private FileUtil() {
    }

    public static List<File> getDellFailFiles() {
        return DELL_FAIL_FILES;
    }

    public static void createDir(File originalData) {
        if (!originalData.exists()) {
            boolean flag = originalData.mkdirs();
            if (!flag) {
                log.error("create dirs is fail: {}", originalData.getAbsolutePath());
            }
        }
    }

    public static String readAllContext(String configFile) {
        File file = null;
        try {
            file = ResourceUtils.getFile("classpath:mapping/" + configFile);
        } catch (FileNotFoundException e) {
            log.error("", e);
        }
        if (file == null) {
            return null;
        }
        byte[] filecontent = new byte[Math.toIntExact(file.length())];
        try (FileInputStream in = new FileInputStream(file)) {
            int length = in.read(filecontent);
            if (length != file.length()) {
                log.warn("读取文件内容的大小不一致。");
            }
            return new String(filecontent, StandardCharsets.UTF_8);
        } catch (IOException e) {
            log.error("", e);
        }
        return null;
    }

    public static void safeDeleteFile(File file) {
        if (file == null || !file.exists()) {
            return;
        }
        if (file.isFile()) {
            deleteSingleFile(file);
        } else {
            File[] dirs = file.listFiles();
            for (File file1 : dirs) {
                safeDeleteFile(file1);
            }
            deleteSingleFile(file);
        }
    }

    private static void deleteSingleFile(File file) {
        try {
            Files.delete(file.toPath());
        } catch (IOException e) {
            log.error("删除文件失败：{}", file.getAbsolutePath(), e);
            DELL_FAIL_FILES.add(file);
        }
    }

    public static void deleteFile(File file) {
        if (file.exists()) {
            try {
                Files.delete(file.toPath());
            } catch (IOException e) {
                log.error("", e);
            }
        }
    }

    public static File findParentFile(File file) {
        return file.getParentFile();
    }
}
